//
//  NovelShelfViewController.m
//  JianChaRiBao
//
//  Created by yuzhou on 13-6-3.
//  Copyright (c) 2013年 wzyk. All rights reserved.
//

#import "NovelShelfViewController.h"
#import "NovelCell.h"
#import "NovelInfoViewController.h"
#import "AppDelegate.h"
#import "DataBase.h"
#import "ASIDownloadCache.h"
@interface NovelShelfViewController ()

@end

@implementation NovelShelfViewController
- (void)showLoadingView
{
    if (loadingView.superview) {
        return;
    }
    if (loadingView == nil) {
        loadingView = [[[ABSpringLoadingView alloc] initWithFrame:lastReadView.frame] autorelease];
    }
    loadingView.alpha = 0;
    [self.view addSubview:loadingView];
    [UIView animateWithDuration:0.3 animations:^{
        loadingView.alpha = 1;
    }];
}

- (void)removeloadingView
{
    if (loadingView) {
        [UIView animateWithDuration:0.3 animations:^{
            loadingView.alpha = 0;
        } completion:^(BOOL finished) {
            [loadingView removeFromSuperview];
            loadingView = nil;
        }];
    }
}


- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}
- (IBAction)backClicked:(id)sender {

    [self.navigationController popViewControllerAnimated:YES];
}
- (IBAction)lastRead:(id)sender {
    lastRead.selected = YES;
    downloaded.selected = NO;
    lastReadView.hidden = NO;
    downloadedView.hidden = YES;
    if (![[AuthorManager defaultManager] hasLoggedIn]) {
//        ABPromptView * abp = [[[ABPromptView alloc]initWithTitle:@"请先登录"]autorelease];
//        [abp show];
        lastReadView.hidden = YES;

    }else{
        [self getRecentlyInfo];
    }
}
- (IBAction)downloaded:(id)sender {
    downloaded.selected = YES;
    lastRead.selected = NO;
    lastReadView.hidden = YES;
    downloadedView.hidden = NO;
    NSArray * array = [[DataBase shareDB] selectInfo];
    [downloadArray removeAllObjects];
    for (NSDictionary * dict in array) {
        ASIHTTPRequest * request = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:[[NSString stringWithFormat:NovelChapterInfoURL,[dict objectForKey:@"nc_id"]] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]];
//        NSLog(@"request :%@",request.url.absoluteString);
        if ([[ASIDownloadCache sharedCache] isCachedDataCurrentForRequest:request]) {
            [downloadArray addObject:dict];
        }
    }
    if (downloadArray && downloadArray.count != 0) {
        [downloadedView reloadData];
    }else{
        downloadedView.hidden = YES;
        ABPromptView * abp = [[[ABPromptView alloc]initWithTitle:@"还没有下载任何图书"]autorelease];
        [abp show];
    }

}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    shouldSwipeBack = YES;
    
    UIView *bgView = [[UIView alloc] init];
    bgView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"bookshelf_cell_bg"]];
    UIView *bgView1 = [[UIView alloc] init];
    bgView1.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"bookshelf_cell_bg"]];

    downloadedView.backgroundView = bgView1;
    downloadedView.backgroundViewExtendsDown = YES;
    downloadedView.leftContentInset = 20;
    downloadedView.rightContentInset = 20;
    downloadedView.contentInset = UIEdgeInsetsMake(0, 0, 1, 0);

    lastReadView.backgroundView = bgView;
    lastReadView.backgroundViewExtendsDown = YES;
    lastReadView.leftContentInset = 20;
    lastReadView.rightContentInset = 20;
    lastReadView.contentInset = UIEdgeInsetsMake(0, 0, 1, 0);
    mDataArray = [[NSMutableArray alloc]initWithCapacity:0];
    downloadArray = [[NSMutableArray alloc]initWithCapacity:0];
    [bgView release];
    [bgView1 release];
}
-(void)viewWillAppear:(BOOL)animated{
//隐藏最近阅读
//    if (lastRead.selected) {
//        if (![[AuthorManager defaultManager] hasLoggedIn]) {
//            ABPromptView * abp = [[[ABPromptView alloc]initWithTitle:@"你还没有登陆"]autorelease];
//            [abp show];
//            lastReadView.hidden = YES;
//
//        }else{
//            [self getRecentlyInfo];
//        }
//    }
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    NSArray * array = [[DataBase shareDB] selectInfo];
    [downloadArray removeAllObjects];
    for (NSDictionary * dict in array) {
        ASIHTTPRequest * request = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:[[NSString stringWithFormat:NovelChapterInfoURL,[dict objectForKey:@"nc_id"]] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]];
        //        NSLog(@"request :%@",request.url.absoluteString);
        if ([[ASIDownloadCache sharedCache] isCachedDataCurrentForRequest:request]) {
            [downloadArray addObject:dict];
        }
    }
    if (downloadArray && downloadArray.count != 0) {
        downloadedView.hidden = NO;
        reLabel.hidden = YES;
        [downloadedView reloadData];
    }else{
        downloadedView.hidden = YES;
        reLabel.hidden = NO;
    }
    

}

-(void)getRecentlyInfo{
    [self showLoadingView];
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        id obj = [[DataRequest sharedRequest] getNovelRecentlyInfo];
        dispatch_async(dispatch_get_main_queue(), ^{
            [self removeloadingView];
            [mDataArray removeAllObjects];
            [mDataArray addObjectsFromArray:[obj objectForKey:@"result"]];

            [lastReadView reloadData];
        });
    });
}
-(NSUInteger)numberOfItemsInGridView:(AQGridView *)gridView{
    if (gridView == lastReadView) {
        return mDataArray.count;
    }
    return downloadArray.count;
}
-(AQGridViewCell *)gridView:(AQGridView *)gridView cellForItemAtIndex:(NSUInteger)index{
    if (gridView == lastReadView) {
        static NSString *CellIdentify = @"cellID";
        NovelCell * cell = (NovelCell *)[gridView dequeueReusableCellWithIdentifier:CellIdentify];
        if (cell == nil) {
            cell = [[NovelCell alloc]initWithFrame:CGRectMake(0, 0, 70, 100) reuseIdentifier:CellIdentify];
        }
        cell.novelInfo = [mDataArray objectAtIndex:index];
        
        [cell updateDisplayWithImageStr:@"image"];
        
        return cell;
 
    }else{
        static NSString *CellIdentify = @"cellID";
        NovelCell * cell = (NovelCell *)[gridView dequeueReusableCellWithIdentifier:CellIdentify];
        if (cell == nil) {
            cell = [[NovelCell alloc]initWithFrame:CGRectMake(0, 0, 70, 100) reuseIdentifier:CellIdentify];
        }
        cell.novelInfo = [downloadArray objectAtIndex:index];
        
        [cell updateDisplayWithImageStr:@"cover_image"];
        
        return cell;

    }
}
-(CGSize)portraitGridCellSizeForGridView:(AQGridView *)gridView{
    return CGSizeMake(80, 150);
}
- (CGRect)gridView:(AQGridView *)gridView adjustCellFrame:(CGRect)cellFrame withinGridCellFrame:(CGRect)gridCellFrame
{
    cellFrame.origin.y -= 5;
    return cellFrame;
}
-(void)gridView:(AQGridView *)gridView didSelectItemAtIndex:(NSUInteger)index{
    NovelInfoViewController * novelInfoViewController = [[[NovelInfoViewController alloc] initWithNibName:@"NovelInfoViewController" bundle:nil] autorelease];
    if (gridView == lastReadView) {
        novelInfoViewController.basicInfo = [mDataArray objectAtIndex:index];
    }else{
        novelInfoViewController.basicInfo = [downloadArray objectAtIndex:index];
    }
    [[UIApplication rootNavController] pushViewController:novelInfoViewController animated:YES];
    [gridView deselectItemAtIndex:index animated:NO];
    
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)dealloc {
    [mDataArray release];
    [lastRead release];
    [downloaded release];
    [lastReadView release];
    [downloadedView release];
    [reLabel release];
    [super dealloc];
}
- (void)viewDidUnload {
    [lastRead release];
    lastRead = nil;
    [downloaded release];
    downloaded = nil;
    [lastReadView release];
    lastReadView = nil;
    [downloadedView release];
    downloadedView = nil;
    [super viewDidUnload];
}
@end
